package com.qbw.app.module.common.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import com.qbw.app.Config;
import com.qbw.app.R;
import com.qbw.app.databinding.FragmentWebviewBinding;
import com.qbw.app.manager.UserManager;
import com.qbw.app.model.User;
import com.qbw.app.module.common.activity.WebViewActivity;
import com.qbw.app.module.common.util.CountryUtil;
import com.qbw.core.base.BaseFragment;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by qbw on 2018/4/4.
 */

public class WebViewFragment extends BaseFragment<FragmentWebviewBinding> {

    public static final int FLAG_DISPATCH = 1;

    private String mUrl;
    private int mFlag;//等同于WebViewActivity
    private String mPhone;

    public static WebViewFragment createInstance(String url) {
        return createInstance(url, 0, "");
    }

    public static WebViewFragment createInstance(String url, int flag, String phone) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle args = new Bundle();
        args.putString(WebViewActivity.KEY_URL, url);
        args.putInt(WebViewActivity.KEY_FLAG, flag);
        args.putString(WebViewActivity.KEY_PHONE, phone);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_webview;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getArguments() : savedInstanceState;
        mUrl = args.getString(WebViewActivity.KEY_URL);
        mFlag = args.getInt(WebViewActivity.KEY_FLAG);
        mPhone = args.getString(WebViewActivity.KEY_PHONE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        return view;
    }

    @Override
    protected void onInit() {
        super.onInit();
        final WebView webview = mBinding.webview;
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //两者都可以
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //设置WebChromeClient类
        webview.setWebChromeClient(new WebChromeClient() {

            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                Activity activity = getActivity();
                if(activity instanceof WebViewActivity){
                    ((WebViewActivity) activity).onReceiveTitle(title);
                }
            }

            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                //mProgress.setProgress(newProgress);
                //mProgress.setVisibility(newProgress >= 100 ? View.GONE : View.VISIBLE);
            }
        });


        //设置WebViewClient类
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view,
                                           final SslErrorHandler handler,
                                           SslError error) {
                if (!Config.isGoogleChannel()) {
                    handler.proceed();
                    return;
                }
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage(R.string.notification_error_ssl_cert_invalid);
                builder.setPositiveButton(R.string.on_continue,
                                          new DialogInterface.OnClickListener() {
                                              @Override
                                              public void onClick(DialogInterface dialog,
                                                                  int which) {
                                                  handler.proceed();
                                              }
                                          });
                builder.setNegativeButton(R.string.on_cancel,
                                          new DialogInterface.OnClickListener() {
                                              @Override
                                              public void onClick(DialogInterface dialog,
                                                                  int which) {
                                                  handler.cancel();
                                              }
                                          });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);//设置不用系统浏览器打开,直接显示在当前Webview
                return true;
            }

            //设置加载前的函数
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                //beginLoading.setText("开始加载了");
            }

            //设置结束加载函数
            @Override
            public void onPageFinished(WebView view, String url) {
                //endLoading.setText("结束加载了");
                if (!webview.getSettings().getLoadsImagesAutomatically()) {
                    webview.getSettings().setLoadsImagesAutomatically(true);
                }
            }
        });

        if (mFlag == FLAG_DISPATCH) {
            Map<String, String> headers = new HashMap<>();
            User user = UserManager.getInstance().getUser();
            headers.put("token", user.getToken());
            headers.put("phone", mPhone);
            headers.put("languageId", CountryUtil.getLanguageId() + "");
            mBinding.webview.loadUrl(String.format("%s?timestamp=%d",
                                                   mUrl,
                                                   System.currentTimeMillis()), headers);
        } else {
            mBinding.webview.loadUrl(mUrl);
        }
    }
}
